package com.wyj.controller;

import com.wyj.interceptor.AlphaInterceptor;
import com.wyj.pojo.Comment;
import com.wyj.pojo.DiscussPost;
import com.wyj.pojo.Page;
import com.wyj.pojo.User;
import com.wyj.service.DiscussPostService;
import com.wyj.service.imp.CommentServiceImp;
import com.wyj.service.imp.ElasticsearchServiceImp;
import com.wyj.service.imp.LikeServiceImp;
import com.wyj.service.imp.UserServiceImp;
import com.wyj.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author 王永杰
 * @Description 描述该类的做什么用
 * @since 2022/7/12
 */

@Controller
public class DiscussPostController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(DiscussPostController.class);


    @Autowired
    DiscussPostService discussPostService;

    @Autowired
    UserServiceImp userServiceImp;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    CommentServiceImp commentServiceImp;

    @Autowired
    LikeServiceImp likeServiceImp;

    @Autowired
    ElasticsearchServiceImp elasticsearchServiceImp;


    @Autowired
    RedisUtil redisUtil;



    @RequestMapping("/detail")
    public String getDetail() {
        return "/site/discuss-detail";
    }


    /**
     * @param title, content]:
     * @Description 处理发帖的异步请求
     * @retuen java.lang.String:返回类型  我们需要处理的话  就是统一处理
     * @author wyj
     * @since 2022/7/12 18:56
     */

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @ResponseBody
    public String addDiscuss(String title, String content) {

        User user = hostHolder.getUser();

        if (user == null) {
            return CommunityUtil.getJsonString(1, "还未登录");
        }

//        System.out.println(user);

        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setContent(content);
        post.setTitle(title);
        post.setCreateTime(new Date());

        discussPostService.addDiscussPost(post);

        //将即将发布的帖子装进El服务器当中
        elasticsearchServiceImp.saveDiscussPost(post);

        //计算帖子分数
        String postScore = RedisKeyUtil.getPostScore();
        redisUtil.sSet(postScore,post.getId());


        return CommunityUtil.getJsonString(1, "发帖成功");

    }

    //显示帖子内容
    @RequestMapping(value = "/getDiscussPost/{id}", method = RequestMethod.GET)
    public String getDiscussPost(@PathVariable("id") int id, Model model, Page page) {

        DiscussPost post = discussPostService.getDiscussPost(id);
        User user = userServiceImp.getUserById(post.getUserId());

        //将当前的帖子跟作者信息存进去
        model.addAttribute("post", post);
        model.addAttribute("user", user);

        //设置分页信息
        page.setLimit(5);//每页5条数据
        page.setPath("/getDiscussPost/"+id);
        page.setRows(post.getCommentCount());

        //点赞
        long likeCount = likeServiceImp.findEntityLikeCount(ENTITY_TYPE_POST,post.getId());
        int likeStatus = likeServiceImp.findEntityLikeStatus(user.getId(),ENTITY_TYPE_POST,post.getId());

        model.addAttribute("likeCount",likeCount);
        model.addAttribute("likeStatus",likeStatus);

        //评论:给帖子的评论
        //回复:给评论的评论 //评论的类型是 entity_id = 2
        //这里的target_id是帖子的id
        //commentList 遍历所有的评论
        //commentVoList List<Map<String,Object>>: 将每一个评论对应的所有信息 用map进行封装
        //commentVo:单个评论所对应的信息  可能有评论该信息的用户 等等
        List<Comment> commentList = commentServiceImp.getCommentsByEntity(ENTITY_TYPE_POST,post.getId(), page.getOffset(), page.getLimit());

        //评论VO列表 这个list 装的是 很多条的评论  用map容器来装入每一条的评论的具体内容
        ArrayList<Map<String, Object>> commentVoList = new ArrayList<>();

        if (commentList != null) {
            for (Comment comment : commentList) {
                //评论VO
                Map<String, Object> commentVo = new HashMap<>();
                //评论
                commentVo.put("comment", comment);
                //作者  每个评论都会有一个作者的id
                commentVo.put("user", userServiceImp.getUserById(comment.getUserId()));

                //查询具体帖子的点赞数
                likeCount = likeServiceImp.findEntityLikeCount(ENTITY_TYPE_POST, comment.getEntityId());
                //查询 已赞 跟 赞
                likeStatus = likeServiceImp.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_POST, comment.getEntityId());

                commentVo.put("likeCount",likeCount);
                commentVo.put("likeStatus",likeStatus);


                //回复列表  评论的回复
                //ENTITY_TYPE_COMMENT : entity_id = 2,2代表的是这个评论的内容是 针对评论的 
                //这里的target_id是 每一条评论的id
                List<Comment> replyList = commentServiceImp.getCommentsByEntity(ENTITY_TYPE_COMMENT,comment.getId(), 0, Integer.MAX_VALUE);

                logger.info("回复评论的大小:"+replyList.size());


                //回复的VO列表 每一条回复也对应内容,
                //每个回复也是在评论的那个表当中
                ArrayList<Map<String, Object>> replyVoList = new ArrayList<>();

                if (replyList != null) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        //回复
                        replyVo.put("reply", reply);

                        logger.info("回复评论的内容"+reply.getContent());

                        //作者 获取每个评论的作者信息
                        replyVo.put("user", userServiceImp.getUserById(reply.getUserId()));
                        //获取回复目标
                        // 如果target == 0的话  那就是  自己评论自己
                        User target = reply.getTargetId() == 0 ? null : userServiceImp.getUserById(reply.getTargetId());
                        replyVo.put("target", target);

                        //查询具体帖子的点赞数
                        likeCount = likeServiceImp.findEntityLikeCount(ENTITY_TYPE_POST, comment.getEntityId());
                        //查询 已赞 跟 赞
                        likeStatus = likeServiceImp.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, reply.getEntityId());

                        replyVo.put("likeCount",likeCount);
                        replyVo.put("likeStatus",likeStatus);

                        //把一条评论的评论添加进去
                        replyVoList.add(replyVo);
                    }
                }
                //将回复的内容对应的集合replyVoList 装进map中
                commentVo.put("replies",replyVoList);

                //获取  每条评论回复数量
                //帖子  帖子的评论  帖子评论的回复
                //帖子的 id entity_id
                //评论的 id comment.getId();
                int comments = commentServiceImp.getComments(ENTITY_TYPE_COMMENT, comment.getId());

                commentVo.put("replyComment",comments);

                commentVoList.add(commentVo);
            }
        }

        model.addAttribute("comments",commentVoList);
        return "/site/discuss-detail";
    }


}
